<?php
defined('EXEC') or die();
$transacao = 'inventario';

Controller::addHead('jquery.multiselects-0.3', 'js');
Controller::addHead("jquery.price_format.2.0.min");

if(!$auth->isRead($transacao)){
	Util::info(Config::AUTH_MESSAGE);
	return true;
}

$form 			= false;
$rowEdit 		= array();
$table 			= 'tethys.tb_preco_item';
$tablepk 		= 'cd_inventario';
$tableEdit      = ' tethys.tb_itens I INNER JOIN TETHYS.TB_UNIDADE_MEDIDA UI ON I.cd_unidade_principal =UI.CI_UNIDADE_MEDIDA ';
$insert         ='';
$faixa 			= 10; //Faixa de páginas que irão ser mostradas paginação (google)
$dif 			= 5; //A diferença que a faixa de páginas irão começar a caminhar (google)
$p 				= (@$_GET['p'] ? $_GET['p'] : 1);
$id_update      =@$_POST['id_update'];
$id_insert      =@$_POST['id_insert'];
$ds_tabela      ='NEIDE NOIVAS';
$id_categoria   =@$_POST['hdn_categoria'];
$id_grupo       =@$_POST['hdn_grupo'];
$id_classe      =@$_POST['hdn_classe'];
$fields         =" ci_item, ds_item, abv_unidade";
$pesquisar      =@$_POST['pesq'];


// Inclusão de um registro
if(@$_POST['item'] && @$_POST['vlr'] && isset($id_insert)){

	//$nr_inventariodigitado = $_POST['cd_inventario'];
	$ds_tabela = $_POST['hdn_ds_tabela'];
	$item = $_POST['item'];
	$pitem = $_POST['pitem'];
	$vlr = str_replace('R$','',str_replace('.','',$_POST['vlr']));
	$vlr = str_replace(',','.',$vlr);
	$nm_usuario = strtoupper($user['nm_login']);

	for($i=0;$i<count($item);$i++){
		if($vlr[$i]<>'0.00'){
			if($pitem[$i]=='0'){
				$insert .=" insert into $table (ds_tabela, cd_item ,nr_preco,nm_usuario,fl_ativa)
					values('".$ds_tabela."',".$item[$i].",'".$vlr[$i]."','". $nm_usuario."',true);";
			}else{
				$insert .= " update $table set nr_preco='".$vlr[$i]."' where ci_preco_item=".$pitem[$i].";" ;
			}
		}
	}

	if(execute($insert)){
		Controller::setInfo('Tabela de Preço', 'Tabela de preços inserida com sucesso!', 'success', 'info-circle', 3500);
		Controller::redirect(Util::setLink(array('form=null', 'db=null', 'del=null')));
	}
	else{
		Util::notice('TABELA DE PREÇOS', 'Ocorreu um erro!', 'error');
	}
}else{

	//Consulta no banco e mecânica de paginação
	$where = " where 1=1 ";

	$tablePreco  = " tethys.tb_itens I INNER JOIN TETHYS.TB_UNIDADE_MEDIDA UI ON I.cd_unidade_principal =UI.CI_UNIDADE_MEDIDA ";
	$tablePreco .= " inner JOIN TETHYS.tb_preco_item PI ON I.CI_ITEM=PI.CD_ITEM ";
	$wherepreco = " where upper(pi.ds_tabela) like upper('$ds_tabela') ";
	$sqlpreco=" select * from $tablePreco $wherepreco order by ds_item asc limit {$limitPagina} offset ".(($p - 1) * $limitPagina);
	$queryp = query($sqlpreco);


	if (!empty($_POST['search1']) || !empty($_POST['search2']) || !empty($_POST['search3']) || !$form){

		if(isset($_POST['search1']) && (!empty($_POST['search1'])) ){
			$term = addslashes($_POST['search1']);
			if (!empty($term)){
				$where .=  " and cd_categoria ={$term} ";}
		}
		if(isset($_POST['search2']) && (!empty($_POST['search2'])) ){
			$term = addslashes($_POST['search2']);
			if (!empty($term)){
				$where .=  " and cd_grupo = {$term} ";}
		}
		if(isset($_POST['search3']) && (!empty($_POST['search3'])) ){
			$term = addslashes($_POST['search3']);
			if (!empty($term)){
				$where .=  " and cd_classe= {$term} ";}
		}
	}
	if(($where != '')){
		$campo=" 0 as nr_preco ";

		if (isset($ds_tabela) && (!empty($ds_tabela))) {
			$tableEdit .= " left JOIN
					(select * from TETHYS.tb_preco_item PI where upper(pi.ds_tabela)
					like upper('%$ds_tabela%') and pi.fl_ativa=TRUE
	 				)pi on I.CI_ITEM=PI.CD_ITEM ";
			$campo=" coalesce(pi.nr_preco,0) as nr_preco ";
		}else{
			$tableEdit .= " left JOIN
					(select * from TETHYS.tb_preco_item PI where pi.fl_ativa=TRUE
	 				)pi on I.CI_ITEM=PI.CD_ITEM ";
			$campo=" coalesce(pi.nr_preco,0) as nr_preco ";
		}

		$sql=" select i.*,ui.*,coalesce(pi.ci_preco_item,0) as ci_preco_item,$campo from $tableEdit $where order by ds_item asc limit {$limitPagina} offset ".(($p - 1) * $limitPagina);
		$sqlc=" select count(*) as num from $tableEdit $where ";

		$query = query($sql);
		$rowNum = query($sqlc)->fetch();
		$registros = $rowNum['num'];
		$paginacao = Util::pagination($registros, 4);
	}
}

?>
<style type="text/css">
	.overlay {
		visibility: hidden;
		position: absolute;
		left: 20%;
		top: 30%;
		width: 55%;
		height: 38%;
		text-align: left;
		z-index: 1000;
		background-color: #CCC;
	}

	ul.none {
		list-style-type: none;
		display: inline;
	}

	#funcoes ul {
		padding: 0px;
		margin: 0px;
		float: left;
		width: 100%;
		background-color: #EDEDED;
		list-style: none;
	}

	#funcoes ul li {
		display: inline;
	}

	#funcoes ul li a {
		padding: 2px 10px;
		float: left;
		/* visual do link */
		background-color: #EDEDED;
		color: #333;
		text-decoration: none;
		border-bottom: 3px solid #EDEDED;
	}

	#funcoes ul li a:hover {
		background-color: #D6D6D6;
		color: #6D6D6D;
		border-bottom: 3px solid #EA0000;
	}
</style>
<h3><i class="glyphicon glyphicon-user"></i> Tabela de Preços -	<?php echo(!isset($_GET['form']) ? 'Pesquisa' : (@$_GET['form'] > 0 ? 'Edição' : 'Cadastro')); ?></h3>
<?php if (!isset($_GET['form'])) { ?><a href="<?php echo Util::setLink(array('form=0')); ?>" class="command-page"><span class="fa fa-plus-square"></span> Novo</a>
<?php } else { ?>
	<a href="#" class="command-page" onclick="window.location='?page=cadastros/tabela_precos';"><span class="fa fa-reply"></span> Voltar</a>
<?php } ?>

<div class="panel panel-default">
	<div class="panel-body">
		<div id="alerts"></div>
		<?php if(!isset($_GET['form'])){ ?>
		<form action="<?php echo Util::setLink(array('p=null')); ?>"  method="post" class="form">
			<div class="row">
				<div class="col-md-4">
					<div class="form-group">
						<label class="control-label">CATEGORIA:</label>
						<select name="search1" id="search1"	class="form-control" onchange="SelecionaCategoria(this);">
							<?php if($_GET['form'] == 0){
								$sql="select ci_categoria_item, ds_categoria_item from tethys.tb_categoria_item order by ds_categoria_item";
								echo '<option value="" >Selecione uma categoria</option>';
								$rs = Connection::query($sql);
								while($row = $rs->fetch()){
									$select = $row["ci_categoria_item"] == $id_categoria ? "selected" : "";
									echo "<option value=\"".@$row["ci_categoria_item"]."\" $select >".$row["ds_categoria_item"]."</option>";
								}
							}?>
						</select>
					</div>
				</div>
				<div class="col-md-4">
					<div class="form-group">
						<label class="control-label">GRUPO:</label>
						<select name="search2" id="search2"	class="form-control" onchange="SelecionaGrupo(this);">
							<?php if($_GET['form'] == 0){
								$sql="select ci_grupo_item, ds_grupo_item from tethys.tb_grupo_item order by ds_grupo_item";
								echo '<option value="" >Selecione um grupo</option>';
								$rs = Connection::query($sql);
								while($row = $rs->fetch()){
									$select = $row["ci_grupo_item"] == $id_grupo ? "selected" : "";
									echo "<option value=\"".@$row["ci_grupo_item"]."\" $select>".$row["ds_grupo_item"]."</option>";
								}
							}?>
						</select>
					</div>
				</div>
				<div class="col-md-4">
					<div class="form-group">
						<label class="control-label">CLASSE:</label>
						<select name="search3" id="search3"	class="form-control" onchange="SelecionaClasse(this);">
							<?php if($_GET['form'] == 0){
								$sql="select ci_classe_item, ds_classe_item from tethys.tb_classe_item order by ds_classe_item";
								echo '<option value="" >Selecione uma classe</option>';
								$rs = Connection::query($sql);
								while($row = $rs->fetch()){
									$select = $row["ci_classe_item"] == $id_classe ? "selected" : "";
									echo "<option value=\"".@$row["ci_classe_item"]."\" $select >".$row["ds_classe_item"]."</option>";
								}
							}?>
						</select>
					</div>
				</div>
				<div class="col-md-1">
					<div class="form-group">
						<label class="control-label">
							<button id="btSearch" title="Pesquisar" class="btn btn-default">
								<span class="fa fa-search"></span>Pesquisar</button>
							<input type="hidden" id="hdn_categoria" name="hdn_categoria" />
							<input type="hidden" id="hdn_grupo" name="hdn_grupo" />
							<input type="hidden" id="hdn_classe" name="hdn_classe" />
							<input type="hidden" id="pesq" name="pesq" value="P" />
					</div>
				</div>
			</div>
		</form>
		<div style="overflow: hidden;">
			<form action="<?php echo Util::setLink(array('del='.$query->rowCount())) ?>" method="post" id="formSearch">
				<div class="table-responsive">
					<table class="table table-striped table-bordered table-hover table-condensed">
						<thead>
							<tr class="ui-widget-header">
								<th>Codigo Item</th>
								<th>Descrição</th>
								<th>UN</th>
								<th>PREÇO</th>
							</tr>
						</thead>
						<tbody>
						<?php
						$count = 0;
						while($row = $query->fetch()){
							echo '<tr>';
							echo' <td>'.$row['ci_item'].'<input type="hidden" id="item[]" name="item[]" value="'.$row['ci_item'].'"></td>';
							echo '<td>'.$row['ds_item'].'<input type="hidden" id="pitem[]" name="pitem[]" value="'.$row['ci_preco_item'].'"></td>
						   	<td>'.$row['abv_unidade'].'</td>
		             		<td>
		             			<input type="text" id="vlr" name="vlr[]" class="form-control vlr number" size="8"
		             				maxlength="12" value="'.$row['nr_preco'].'" >
		             		</td>';
							echo '</tr>';
							$count++;
						}
						?>
						</tbody>
						<tfoot>
							<tr>
								<td colspan="5" align="center">
								<input type="hidden" id="hdn_ds_tabela" name="hdn_ds_tabela" value="<?php echo $ds_tabela;?>" />
								<input type="hidden" id="id_insert" name="id_insert" value="$insert" />
								<br clear="all">
								<button id="btInsertEdit" class="btn btn-default" type="submit">
									<span class="fa fa-floppy-o"></span> Salvar
								</button>
								</td>
							</tr>
						</tfoot>
					</table>
				</div>
			</form>
		</div>
		<?php } ?>
	</div>
</div>
<br clear="all">
<script type="text/javascript">
	function Seleciona_Radio(radio){
		document.getElementById("hdn_radio").value=radio;
	}

	$(function(){
		if($('#hdn_ds_tabela').val()==''){
			$('#btAdd').hide();
		}else{
			$('#btAdd').show();
		}

		$('.vlr').priceFormat({
			prefix: 'R$ ',
			centsSeparator: ',',
			thousandsSeparator: '.'});

	});

	function SelecionaInventario(obj){
		var id = obj.value;
		document.getElementById('hdn_nr_inventario').value= id;
	}
	function SelecionaCategoria(obj){
		var id = obj.value;
		document.getElementById('hdn_categoria').value= id;
	}
	function SelecionaGrupo(obj){
		var id = obj.value;
		document.getElementById('hdn_grupo').value= id;
	}
	function SelecionaClasse(obj){
		var id = obj.value;
		document.getElementById('hdn_classe').value= id;
	}

</script>